<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>心跳机制测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .status.connected {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.disconnected {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .log {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 3px;
            margin: 10px 0;
            max-height: 300px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
            border: 1px solid #dee2e6;
        }
        button {
            padding: 8px 16px;
            margin: 5px;
            cursor: pointer;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #6c757d;
            cursor: not-allowed;
        }
        input {
            padding: 8px;
            margin: 5px;
            width: 300px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin: 20px 0;
        }
        .stat-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            text-align: center;
            border: 1px solid #dee2e6;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #007bff;
        }
        .stat-label {
            color: #6c757d;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>WebSocket心跳机制测试</h1>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-value" id="connection-status">断开</div>
                <div class="stat-label">连接状态</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="heartbeat-count">0</div>
                <div class="stat-label">心跳次数</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="last-heartbeat">-</div>
                <div class="stat-label">最后心跳</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="uptime">0s</div>
                <div class="stat-label">运行时间</div>
            </div>
        </div>
        
        <div>
            <input type="text" id="token-input" placeholder="输入JWT token" />
            <button onclick="connect()">连接</button>
            <button onclick="disconnect()" id="disconnect-btn" disabled>断开</button>
            <button onclick="clearLog()">清空日志</button>
        </div>
        
        <div id="status" class="status disconnected">未连接</div>
        
        <div class="log" id="log"></div>
    </div>

    <script>
        let ws = null;
        let heartbeatTimer = null;
        let heartbeatCount = 0;
        let startTime = null;
        let uptimeTimer = null;
        
        function log(message) {
            const logElement = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            logElement.innerHTML += `[${timestamp}] ${message}\n`;
            logElement.scrollTop = logElement.scrollHeight;
        }
        
        function updateStats() {
            document.getElementById('heartbeat-count').textContent = heartbeatCount;
            if (startTime) {
                const uptime = Math.floor((Date.now() - startTime) / 1000);
                document.getElementById('uptime').textContent = uptime + 's';
            }
        }
        
        function connect() {
            const token = document.getElementById('token-input').value.trim();
            if (!token) {
                log('❌ 请输入JWT token');
                return;
            }
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                log('⚠️ 连接已存在，先断开');
                disconnect();
            }
            
            const wsUrl = `ws://localhost:8081/ws?token=${encodeURIComponent(token)}`;
            log(`🔗 正在连接到 ${wsUrl}...`);
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function(event) {
                log('✅ WebSocket连接建立成功');
                document.getElementById('status').textContent = '已连接';
                document.getElementById('status').className = 'status connected';
                document.getElementById('connection-status').textContent = '已连接';
                document.getElementById('disconnect-btn').disabled = false;
                
                // 启动心跳
                startHeartbeat();
                
                // 记录开始时间
                startTime = Date.now();
                uptimeTimer = setInterval(updateStats, 1000);
            };
            
            ws.onmessage = function(event) {
                const data = JSON.parse(event.data);
                log(`📨 收到消息: ${JSON.stringify(data)}`);
                
                if (data.type === 'ping') {
                    // 收到服务器心跳，回复pong
                    const pongMsg = {
                        type: 'pong',
                        timestamp: Date.now()
                    };
                    ws.send(JSON.stringify(pongMsg));
                    log('💓 收到服务器心跳，回复pong');
                } else if (data.type === 'pong') {
                    // 收到pong响应
                    heartbeatCount++;
                    document.getElementById('last-heartbeat').textContent = new Date().toLocaleTimeString();
                    log('💓 收到pong响应');
                    updateStats();
                }
            };
            
            ws.onclose = function(event) {
                log(`❌ 连接关闭 (代码: ${event.code}, 原因: ${event.reason})`);
                document.getElementById('status').textContent = '连接已断开';
                document.getElementById('status').className = 'status disconnected';
                document.getElementById('connection-status').textContent = '断开';
                document.getElementById('disconnect-btn').disabled = true;
                
                // 停止心跳和计时器
                stopHeartbeat();
                if (uptimeTimer) {
                    clearInterval(uptimeTimer);
                    uptimeTimer = null;
                }
            };
            
            ws.onerror = function(error) {
                log(`❌ 连接错误: ${error}`);
            };
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        function startHeartbeat() {
            if (heartbeatTimer) {
                clearInterval(heartbeatTimer);
            }
            
            heartbeatTimer = setInterval(() => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    const heartbeatMsg = {
                        type: 'ping',
                        timestamp: Date.now()
                    };
                    ws.send(JSON.stringify(heartbeatMsg));
                    log('💓 发送心跳消息');
                }
            }, 30000); // 30秒发送一次心跳
        }
        
        function stopHeartbeat() {
            if (heartbeatTimer) {
                clearInterval(heartbeatTimer);
                heartbeatTimer = null;
            }
        }
        
        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }
        
        // 页面加载时的提示
        log('心跳机制测试页面已加载');
        log('请输入JWT token并点击连接按钮开始测试');
    </script>
</body>
</html> 